import 'dart:async';

import 'package:aero_frisbee/app/model/af_coin_product_model/af_coin_product_model.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import 'view_model/af_app_purchase_view_model.dart';
import 'views/af_app_purchase_cell.dart';

class AfAppPurchaseScreen extends ConsumerStatefulWidget {
  const AfAppPurchaseScreen({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfAppPurchaseScreenState();
}

class _AfAppPurchaseScreenState extends ConsumerState<AfAppPurchaseScreen> {
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  @override
  Widget build(BuildContext context) {
    ref.listen(getPurchaseDetailsServiceProvider, (previousData, newData) {
      final retItem =
          newData.maybeWhen(ready: ((data) => data), orElse: () => null);

      final isError = newData.maybeWhen(
        orElse: () => false,
        error: (data) => true,
      );
      if (isError) {
        "pay fail".toast();
        SmartDialog.dismiss();
        return;
      }

      if (retItem != null && retItem.item2.isNotEmpty) {
        /// to pay for
        _buyConsumable(productDetail: retItem.item2[0]);
      }
    });

    ref.listen(verifyPurchaseServiceProvider, (previousData, newData) {
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "pay success".toast();
        SmartDialog.dismiss();
        final item = ref.read(getPurchaseDetailsServiceProvider).maybeWhen(
              orElse: () => null,
              ready: (data) => data.item3,
            );
        ref
            .read(appCacheServiceProvider.notifier)
            .updateAvailableCoins(item ?? 0);
      }
    });

    return Scaffold(
      backgroundColor: const Color(0xff333333),
      appBar: AppBar(
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).maybePop();
          },
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 20,
              ),
              child: Assets.images.mine.navWhiteBack.image(width: 25),
            ),
          ),
        ),
        title: const Text(
          'Coin Shop',
          style: TextStyle(
            color: Color(0xffffffff),
            fontWeight: FontWeight.normal,
            fontSize: 16,
          ),
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        ),
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              final curLogin = ref.read(curlUserInfoProvider);
              if (curLogin != null) {
                AFLogPvManger.stat(page: AFLogPages.customer);
                context.pushNamed(RouteUri.messageDetai, queryParams: {
                  "userId": curLogin.userServiceAccountId ?? ''
                });
              }
            },
            child: Padding(
              padding: const EdgeInsets.only(
                right: 20,
              ),
              child: Assets.images.mine.kefuBtn.image(width: 25),
            ),
          )
        ],
      ),
      body: Stack(
        children: [
          Positioned(
            top: 20,
            left: 0,
            right: 0,
            child: Align(
              alignment: Alignment.topCenter,
              child: SizedBox(
                height: 160,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: AspectRatio(
                    aspectRatio: 338 / 150,
                    child: Assets.images.mine.coinShopHeaderBg.image(),
                  ),
                ),
              ),
            ),
          ),
          Column(
            children: [
              const SizedBox(
                height: 20,
              ),
              AspectRatio(
                aspectRatio: 338 / 23,
                child: Container(),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 30),
                margin: const EdgeInsets.symmetric(horizontal: 22),
                child: Align(
                  alignment: Alignment.topLeft,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${ref.watch(curlUserInfoProvider.select(
                          (value) => value?.userInfoModel?.availableCoins,
                        ))}',
                        style: const TextStyle(
                          color: Color(0xff303507),
                          fontWeight: FontWeight.w900,
                          fontSize: 32,
                        ),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      const SizedBox(
                        height: 20,
                      ),
                      const Text(
                        'My Coins',
                        style: TextStyle(
                          color: Color(0xff303507),
                          fontWeight: FontWeight.w900,
                          fontSize: 20,
                        ),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      )
                    ],
                  ),
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              Expanded(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Container(
                    decoration: const BoxDecoration(
                      color: Color(0xffF8F8F8),
                    ),
                    child: ref.watch(getAfCoinProductFutureProvider).maybeWhen(
                          orElse: () => Container(),
                          loading: () =>
                              const Center(child: CircularProgressIndicator()),
                          data: (data) => _buildBody(data),
                        ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  _buildBody(List<AfCoinProductModel> data) {
    return ListView.separated(
      padding: const EdgeInsets.only(top: 20),
      itemBuilder: (context, index) {
        final item = data[index];
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            SmartDialog.showLoading(
              backDismiss: false,
              builder: (_) => const CircularProgressIndicator(),
            );
            ref
                .read(getPurchaseDetailsServiceProvider.notifier)
                .getPurchaseDetails(
              kIds: {item.code!},
              exchangeCoin: item.exchangeCoin!,
            );
          },
          child: AfAppPurchaseCell(
            item: item,
          ),
        );
      },
      separatorBuilder: (context, index) => const SizedBox(
        height: 12,
      ),
      itemCount: data.length,
    );
  }

  _buyConsumable({required ProductDetails productDetail}) async {
    var purchaseParam = PurchaseParam(productDetails: productDetail);
    AFLogPvManger.stat(page: AFLogPages.createOrder);
    await InAppPurchase.instance.buyConsumable(purchaseParam: purchaseParam);
  }

  Future<void> _listenToPurchaseUpdated(
      List<PurchaseDetails> purchaseDetailsList) async {
    for (var purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        /// handle pending purchase details
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        "Purchase canceled".toast();
        SmartDialog.dismiss();
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          SmartDialog.dismiss();

          /// handle error
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          ///支付成功
          final item = ref.read(getPurchaseDetailsServiceProvider).maybeWhen(
                orElse: () => null,
                ready: (data) => data.item1,
              );
          if (item != null) {
            ref.read(verifyPurchaseServiceProvider.notifier).verifyPurchase(
                  item: item,
                  purchaseDetails: purchaseDetails,
                );
          } else {
            SmartDialog.dismiss();
          }
        }
        if (purchaseDetails.pendingCompletePurchase) {
          await InAppPurchase.instance.completePurchase(purchaseDetails);
        }
      }
    }
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      AFLogPvManger.stat(page: AFLogPages.purchase);
    });
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    }, onError: (error) {
      // handle error here.
    });
    super.initState();
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  void didUpdateWidget(AfAppPurchaseScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
